<template>
  <div class="app-container">
    <el-form :inline="true">
      <el-form-item label="店铺名称">
        <el-input
          v-model="queryParams.deptName"
          placeholder="请输入店铺名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态">
        <el-select v-model="queryParams.status" placeholder="店铺状态" clearable size="small">
          <el-option
            v-for="dict in statusOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button
          class="filter-item"
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
        >搜索</el-button>
        <el-button
          class="filter-item"
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:dept:add']"
        >新增</el-button>
      </el-form-item>
    </el-form>

    <el-table
      v-loading="loading"
      :data="deptList"
      row-key="deptId"
      default-expand-all
      :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
    >
      <el-table-column prop="deptName" label="店铺名称" width="200"></el-table-column>
      <el-table-column prop="orderNum" label="排序" width="200"></el-table-column>
      <el-table-column prop="status" label="状态" :formatter="statusFormat" width="100"></el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="200">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:dept:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-plus"
            @click="handleAdd(scope.row)"
            v-hasPermi="['system:dept:add']"
          >新增</el-button>
          <el-button
            v-if="scope.row.parentId != 0"
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:dept:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog :visible.sync="dialogVisible">
      <img width="100%" :src="dialogImageUrl" alt="">
    </el-dialog>

    <!-- 添加或修改部门对话框 -->
    <el-dialog :title="title" :visible.sync="open"   top="15px" width="60%">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="24" v-if="form.parentId !== 0">
            <el-form-item label="上级店铺" prop="parentId">
              <treeselect v-model="form.parentId" :options="deptOptions" placeholder="选择上级店铺" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="店铺名称" prop="deptName">
              <el-input v-model="form.deptName" placeholder="请输入店铺名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="支付宝" prop="account">
              <el-input v-model="form.account" placeholder="请输入支付宝账户" maxlength="20" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="店铺简介" prop="description">
              <el-input v-model="form.description"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="店铺标语" prop="promotionInfo">
              <el-input v-model="form.promotionInfo"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="店铺属性">
              <el-select v-model="form.attrIds" multiple placeholder="请选择">
                <el-option
                  v-for="item in attrOptions"
                  :key="item.attrId"
                  :label="item.name"
                  :value="item.attrId"
                  :disabled="item.status == 1"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="店铺分类" prop="categoryIds">
              <el-cascader
                :options="categoryOptions"
                v-model="form.categoryIds"
                change-on-select  filterable clearable
              ></el-cascader>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="显示排序" prop="orderNum">
              <el-input-number v-model="form.orderNum"  :min="1" :max="200" ></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="抽成" prop="percent">
              <el-input-number v-model="form.percent"  :min="0" :max="10" ></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="配送费" prop="floatDeliveryFee">
              <el-input-number v-model="form.floatDeliveryFee" :min="0" :max="20"></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="起送价" prop="floatMinimumOrderAmount">
              <el-input-number v-model="form.floatMinimumOrderAmount" :min="0" :max="100"></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="负责人" prop="leader">
              <el-input v-model="form.leader" placeholder="请输入负责人" maxlength="20" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系电话" prop="phone">
              <el-input v-model="form.phone" placeholder="请输入联系电话" maxlength="11" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="form.email" placeholder="请输入邮箱" maxlength="50" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="部门状态">
              <el-radio-group v-model="form.status">
                <el-radio
                  v-for="dict in statusOptions"
                  :key="dict.dictValue"
                  :label="dict.dictValue"
                >{{dict.dictLabel}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="营业类型" prop="deptType">
              <el-select v-model="form.type" placeholder="请选择">
                <el-option
                  v-for="dict in typeOptions"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="配送方式" prop="noticeType">
              <el-select v-model="form.delivery" placeholder="请选择">
                <el-option
                  v-for="dict in deliveryOptions"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="营业时间" >
              <el-time-select
                placeholder="起始时间"
                v-model="form.startTime"
                :picker-options="{
                start: '05:30',
                step: '00:15',
                end: '23:30'
                }">
              </el-time-select>
              <el-time-select
                placeholder="结束时间"
                v-model="form.endTime"
                :picker-options="{
                start: '05:30',
                step: '00:15',
                end: '23:30',
                minTime: form.startTime
                }">
              </el-time-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="优惠活动">
              <el-select v-model="form.activityValue" @change="selectActivity" :placeholder="form.activityValue">
                <el-option
                  v-for="item in form.options"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
            <el-table
              :data="form.activities"
              align="cneter"
              :row-class-name="tableRowClassName">
              <el-table-column
                prop="icon_name"
                label="活动标题"
                align="cneter"
                width="120">
              </el-table-column>
              <el-table-column
                prop="name"
                label="活动名称"
                align="cneter"
                width="120">
              </el-table-column>
              <el-table-column
                prop="description"
                align="cneter"
                label="活动详情">
              </el-table-column>
              <el-table-column
                label="操作"
                width="120">
                <template slot-scope="scope">
                  <el-button
                    size="small"
                    type="primary"
                    icon="el-icon-delete"
                    @click="handleDeleteActivity(scope.$index)"
                  >删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-col>
          <el-col :span="24">
            <el-form-item label="图片介绍">
              <el-upload
                :headers="headers"
                :action="uploadImgUrl"
                list-type="picture-card"
                :on-success="onSuccess	"
                :file-list="form.fileList"
                :auto-upload="true">
                <i slot="default" class="el-icon-plus"></i>
                <div slot="file" slot-scope="{file}">
                  <img
                    class="el-upload-list__item-thumbnail"
                    :src="file.url" alt=""
                  >
                  <span class="el-upload-list__item-actions">
        <span
          class="el-upload-list__item-preview"
          @click="handlePictureCardPreview(file)"
        >
          <i class="el-icon-zoom-in"></i>
        </span>
        <span
          v-if="!disabled"
          class="el-upload-list__item-delete"
          @click="handleRemove(file)"
        >
          <i class="el-icon-delete"></i>
        </span>
      </span>
                </div>
              </el-upload>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="详细地址" prop="address">
              <div>
                <el-autocomplete
                  v-model="form.address"
                  :fetch-suggestions="querySearch"
                  placeholder="请输入详细地址"
                  style="width: 100%"
                  :trigger-on-focus="false"
                  @select="handleSelect"
                />
                <div style="margin: 5px">
                  <baidu-map class="map" :center="form.mapCenter"  v-if="hackReset" :zoom="mapZoom" :scroll-wheel-zoom="true"  @ready="handlerBMap" />
                </div>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<style>
  .map {
    width: 100%;
    height: 400px;
  }
</style>
<script>
import { listDept, getDept, listAttr,initCategory,treeselect, delDept, addDept, updateDept } from "@/api/system/dept";
import { getToken } from '@/utils/auth'
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  components: { Treeselect },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 表格树数据
      deptList: [],
      // 部门部门树选项
      deptOptions: undefined,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 状态数据字典
      statusOptions: [],
      //配送方式数据字典
      deliveryOptions:[],
      //营业类型数据字典
      typeOptions:[],
      categoryOptions: [],
      // 属性选项
      attrOptions: [],
      // 查询参数
      queryParams: {
        deptName: undefined,
        status: undefined
      },
      // 表单参数
      form: {
        mapCenter: { lng: 0, lat: 0 },
        fileList: [{name: 'food.jpeg', url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100'}, {name: 'food2.jpeg', url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100'}]
      },
      // 表单校验
      rules: {
        parentId: [
          { required: true, message: "上级部门不能为空", trigger: "blur" }
        ],
        deptName: [
          { required: true, message: "部门名称不能为空", trigger: "blur" }
        ],
        orderNum: [
          { required: true, message: "菜单顺序不能为空", trigger: "blur" }
        ],
        account: [
          { required: true, message: "账户不能为空", trigger: "blur" }
        ],
        percent: [
          { required: true, message: "抽成不能为空", trigger: "blur" }
        ],
        floatDeliveryFee: [
          { required: true, message: "配送费不能为空", trigger: "blur" }
        ],
        floatMinimumOrderAmount: [
          { required: true, message: "起送价不能为空", trigger: "blur" }
        ],
        email: [
          {
            type: "email",
            message: "'请输入正确的邮箱地址",
            trigger: ["blur", "change"]
          }
        ],
        phone: [
          {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: "请输入正确的手机号码",
            trigger: "blur"
          }
        ]
      },
      uploadImgUrl: process.env.VUE_APP_BASE_API + "/common/upload", // 上传的图片服务器地址
      headers: {
        Authorization: 'Bearer ' + getToken()
      },
      dialogImageUrl: '',
      dialogVisible: false,
      disabled: false,
      hackReset:false,
      mapZoom: 15,
    };
  },
  created() {
    this.getList();
    this.getDicts("sys_normal_disable").then(response => {
      this.statusOptions = response.data;
    });
    this.getDicts("sys_delivery_mode").then(response => {
      this.deliveryOptions = response.data;
    });
    this.getDicts("sys_dept_type").then(response => {
      this.typeOptions = response.data;
    });
    this.initCategory();
  },
  methods: {
    /** 查询部门列表 */
    getList() {
      this.loading = true;
      listDept(this.queryParams).then(response => {
        this.deptList = response.data;
        this.loading = false;
      });
    },
    /** 查询部门下拉树结构 */
    getTreeselect() {
      treeselect().then(response => {
        this.deptOptions = response.data;
      });
    },
    // 字典状态字典翻译
    statusFormat(row, column) {
      return this.selectDictLabel(this.statusOptions, row.status);
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        deptId: undefined,
        parentId: 100,
        floatDeliveryFee:5,
        floatMinimumOrderAmount:20,
        startTime: '',
        endTime: '',
        type:undefined,
        delivery:undefined,
        description:undefined,
        promotionInfo:undefined,
        deptName: undefined,
        percent:undefined,
        orderNum: undefined,
        leader: undefined,
        phone: undefined,
        email: undefined,
        lng:undefined,
        lat:undefined,
        province:undefined,
        city:undefined,
        district:undefined,
        street:undefined,
        address:undefined,
        mapCenter: { lng: 0, lat: 0 },
        attrIds:[],
        categoryIds: [],
        fileList: [],
        status: "0",
        options: [{
          value: '满减优惠',
          label: '满减优惠'
        }, {
          value: '优惠大酬宾',
          label: '优惠大酬宾'
        }, {
          value: '新用户立减',
          label: '新用户立减'
        }, {
          value: '进店领券',
          label: '进店领券'
        }],
        activityValue: '满减优惠',
        /*activities: [{
          icon_name: '减',
          name: '满减优惠',
          description: '满30减5，满60减8'
        }],*/
        activities: [],
      };
      this.resetForm("form");
    },
    initCategory(){
      initCategory().then(response => {
        const categories = response.data;
        categories.forEach(item => {
          if (item.subCategories.length) {
            const addnew = {
              value: item.categoryId,
              label: item.name,
              level:item.level,
              children: []
            }
            item.subCategories.forEach((subitem, index) => {
              if (index === 0) {
                return
              }
              addnew.children.push({
                value: subitem.categoryId,
                level:subitem.level,
                label: subitem.name
              })
            })
            this.categoryOptions.push(addnew)
          }
        })
      });
    },
    initImg() {
      if(this.form.fileList){
        this.form.fileList.forEach((item, i) => {
          if(item.response&&item.response.url) {
            item.url=item.response.url;
          }
        })
      }
    },
    selectActivity() {
      this.$prompt('请输入活动详情', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }).then(({ value }) => {
        if (value === null) {
          this.$message({
            type: 'info',
            message: '请输入活动详情'
          })
          return
        }
        let newObj = {}
        switch (this.form.activityValue) {
          case '满减优惠':
            newObj = {
              icon_name: '减',
              name: '满减优惠',
              description: value
            }
            break
          case '优惠大酬宾':
            newObj = {
              icon_name: '特',
              name: '优惠大酬宾',
              description: value
            }
            break
          case '新用户立减':
            newObj = {
              icon_name: '新',
              name: '新用户立减',
              description: value
            }
            break
          case '进店领券':
            newObj = {
              icon_name: '领',
              name: '进店领券',
              description: value
            }
            break
        }
        this.form.activities.push(newObj)
      }).catch(() => {
        // this.msgError("取消输入");
      })
    },
    handleDeleteActivity(index) {
      this.form.activities.splice(index, 1)
    },
    tableRowClassName(row, index) {
      if (index === 1) {
        return 'info-row'
      } else if (index === 3) {
        return 'positive-row'
      }
      return ''
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getList();
    },
    /** 新增按钮操作 */
    handleAdd(row) {
      this.reset();
      this.hackReset = false
      this.$nextTick(() => {
        this.hackReset = true
      })
      this.getAttrs();
      this.getTreeselect();
      if (row != undefined) {
        this.form.parentId = row.deptId;
      }
      this.open = true;
      this.title = "添加店铺";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.getTreeselect();
      this.getAttrs();
      getDept(row.deptId).then(response => {
        this.form = response.data;
        this.form.attrIds=response.attrIds;
        this.form.categoryIds=response.categoryIds;
        this.form.mapCenter={ lng:this.form.lng, lat: this.form.lat};
        this.hackReset = false;
        this.$nextTick(() => {
          this.hackReset = true
        })
        this.open = true;
        this.title = "修改店铺";
      });
    },
    /** 提交按钮 */
    submitForm: function() {
      this.initImg();
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.deptId != undefined) {
            updateDept(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              } else {
                this.msgError(response.msg);
              }
            });
          } else {
            addDept(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              } else {
                this.msgError(response.msg);
              }
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$confirm('是否确认删除名称为"' + row.deptName + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delDept(row.deptId);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(function() {});
    },
    handlerBMap({ BMap, map }) {
      this.BMap = BMap
      this.map = map
      let _this=this;
      if (_this.form.lng && _this.form.lat) {
        _this.form.mapCenter.lng = _this.form.lng
        _this.form.mapCenter.lat = _this.form.lat
        _this.mapZoom = 15
        // map.addOverlay(new _this.BMap.Marker(_this.form.mapCenter))
        _this.map.clearOverlays()
        _this.map.addOverlay(new _this.BMap.Marker(_this.form.mapCenter))
      } else {
        var geolocation=new BMap.Geolocation();
        geolocation.getCurrentPosition(function (r) {
          _this.form.mapCenter.lng = r.longitude;
          _this.form.mapCenter.lat = r.latitude
        })
        _this.mapZoom = 10
      }
    },
    querySearch(queryString, cb) {
      var that = this
      var myGeo = new this.BMap.Geocoder()
      myGeo.getPoint(queryString, function(point) {
        if (point) {
          that.form.mapCenter = point
          that.makerCenter(point)
        } else {
          that.form.mapCenter = null
        }
      }, this.locationCity)
      var options = {
        onSearchComplete: function(results) {
          if (local.getStatus() === 0) {
            // 判断状态是否正确
            var s = []
            for (var i = 0; i < results.getCurrentNumPois(); i++) {
              var x = results.getPoi(i)
              var item = { value: x.address + x.title, point: x.point }
              s.push(item)
              cb(s)
            }
          } else {
            cb()
          }
        }
      }
      var local = new this.BMap.LocalSearch(this.map, options)
      local.search(queryString)
    },
    handleSelect(item) {
      var { point } = item
      this.form.mapCenter = point
      let geocoder= new BMap.Geocoder();  //创建地址解析器的实例
      geocoder.getLocation(point,rs=>{
        this.form.lng=point.lng;
        this.form.lat=point.lat;
        this.form.province=rs.addressComponents.province;
        this.form.city=rs.addressComponents.city;
        this.form.district=rs.addressComponents.district;
        this.form.street=rs.addressComponents.street;
      });
      this.makerCenter(point)
    },
    makerCenter(point) {
      if (this.map) {
        this.map.clearOverlays()
        this.map.addOverlay(new this.BMap.Marker(point))
        this.form.mapCenter.lng = point.lng
        this.form.mapCenter.lat = point.lat
        this.mapZoom = 15
      }
    },
    handleRemove(file) {
      this.form.fileList.forEach((item, i) => {
        if(item.url===file.url) {
          this.form.fileList.splice(i, 1)
        }
      })
      },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    /** 查询属性列表 */
    getAttrs() {
      listAttr().then(response => {
        this.attrOptions = response.rows;
      });
    },
    onSuccess(response, file, fileList){
      this.form.fileList=fileList;
    }
  }
};
</script>
